<template>
  <div class="chart-container">
    <VChart v-if="chartOption.series" class="chart" :option="chartOption" autoresize />
    <div v-else class="no-data">图表加载中...</div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { getShowList } from "@/api/material-service/transactions.js";

use([
  CanvasRenderer,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])



const chartOption = ref({})
const operationDict = {
  1: { name: "下料", color: "#5470C6" },
  2: { name: "冲压", color: "#91CC75" },
  3: { name: "折弯", color: "#FAC858" },
  4: { name: "焊接", color: "#EE6666" },
  5: { name: "喷涂", color: "#73C0DE" },
  // 可以继续添加其他工序
};
// 转换数据格式为ECharts需要的格式
const transformData = (apiData) => {
  const seriesData = [];

  apiData.forEach(operation => {


    const operationColor = operationDict[operation.operationId].color;
    // 添加工序总消耗
    seriesData.push({
      name: `${operationDict[operation.operationId].name}`,
      value: operation.materials.reduce((sum, mat) => sum + mat.quality, 0),
      itemStyle: {
        color: operationColor // 为每个工序分配颜色
      }
    });

    // 添加各物料消耗
    operation.materials.forEach(material => {
      seriesData.push({
        name: `${material.materialName} (${material.quality}${material.unitOfMeasure})`,
        value: material.quality,
        itemStyle: {
          color: `${operationColor}80`// 子项使用父项颜色
        }
      });
    });
  });

  return seriesData;
};

// 生成随机颜色


// 获取数据
const fetchData = async () => {
  try {
    const response = await getShowList();
    console.log(response)
    // 假设API返回的data字段包含我们需要的数据
    const apiData = response|| [];

    if (apiData.length === 0) {
      console.warn('无有效数据');
      return;
    }

    initChart(apiData);
  } catch (error) {
    console.error('获取数据失败:', error);
    // 可以在这里设置一个默认的空状态图表
    chartOption.value = {
      title: {
        text: '数据加载失败',
        left: 'center'
      },
      series: []
    };
  }
};

// 初始化图表
const initChart = (data) => {
  const seriesData = transformData(data);

  chartOption.value = {
    title: {
      text: '各工序材料消耗占比',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      show:false,
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 20,
      bottom: 20,
      data: seriesData.map(item => item.name)
    },
    series: [{
      name: '材料消耗',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        formatter: '{b}: {c} ({d}%)'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: true
      },
      data: seriesData
    }]
  };
};

// 组件挂载时自动加载数据
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 300px;
  position: relative;
}
.chart {
  width: 100%;
  height: 100%;
}
.no-data {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #999;
}
</style>